#!/usr/bin/env node

import { execSync } from 'child_process'
import { writeFileSync, existsSync, mkdirSync } from 'fs'
import { join } from 'path'

const REPORT_DIR = 'test-reports'
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')

// Ensure report directory exists
if (!existsSync(REPORT_DIR)) {
  mkdirSync(REPORT_DIR, { recursive: true })
}

console.log('🧪 Running comprehensive test suite...\n')

try {
  // Run tests with coverage
  console.log('📊 Running tests with coverage...')
  const testOutput = execSync('pnpm test:coverage', { 
    encoding: 'utf8',
    stdio: 'pipe'
  })
  
  // Generate test report
  const report = {
    timestamp: new Date().toISOString(),
    status: 'PASSED',
    summary: {
      total: extractMetric(testOutput, /(\d+) passed/),
      passed: extractMetric(testOutput, /(\d+) passed/),
      failed: extractMetric(testOutput, /(\d+) failed/) || 0,
      skipped: extractMetric(testOutput, /(\d+) skipped/) || 0
    },
    coverage: extractCoverage(testOutput),
    output: testOutput
  }
  
  // Save report
  const reportFile = join(REPORT_DIR, `test-report-${timestamp}.json`)
  writeFileSync(reportFile, JSON.stringify(report, null, 2))
  
  console.log('\n✅ Test suite completed successfully!')
  console.log(`📄 Report saved to: ${reportFile}`)
  console.log('\n📊 Test Summary:')
  console.log(`   Total: ${report.summary.total}`)
  console.log(`   Passed: ${report.summary.passed}`)
  console.log(`   Failed: ${report.summary.failed}`)
  console.log(`   Skipped: ${report.summary.skipped}`)
  
  if (report.coverage) {
    console.log('\n📈 Coverage Summary:')
    console.log(`   Lines: ${report.coverage.lines}%`)
    console.log(`   Functions: ${report.coverage.functions}%`)
    console.log(`   Branches: ${report.coverage.branches}%`)
    console.log(`   Statements: ${report.coverage.statements}%`)
  }
  
} catch (error) {
  console.error('❌ Test suite failed!')
  console.error(error.message)
  
  const report = {
    timestamp: new Date().toISOString(),
    status: 'FAILED',
    error: error.message,
    output: error.stdout || error.message
  }
  
  const reportFile = join(REPORT_DIR, `test-report-failed-${timestamp}.json`)
  writeFileSync(reportFile, JSON.stringify(report, null, 2))
  
  console.log(`📄 Error report saved to: ${reportFile}`)
  process.exit(1)
}

function extractMetric(output, regex) {
  const match = output.match(regex)
  return match ? parseInt(match[1]) : null
}

function extractCoverage(output) {
  const coverageMatch = output.match(/All files\s+\|\s+([\d.]+)\s+\|\s+([\d.]+)\s+\|\s+([\d.]+)\s+\|\s+([\d.]+)/)
  if (coverageMatch) {
    return {
      statements: parseFloat(coverageMatch[1]),
      branches: parseFloat(coverageMatch[2]),
      functions: parseFloat(coverageMatch[3]),
      lines: parseFloat(coverageMatch[4])
    }
  }
  return null
}